package com.zhouheng.springbootactiviti.common.web.advice;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.zhouheng.common.base.exception.SysErrorException;
import com.zhouheng.common.base.web.Result;
import com.zhouheng.common.base.web.WebCode;
import com.zhouheng.common.base.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;


@RestControllerAdvice
@Slf4j
@Component
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleBindException(BindException e, HttpServletRequest request) {
        Map<String, Collection<String>> errors = fetchBindingErrors(e.getBindingResult());
        return Result.error(WebCode.ARG_INVALID, request.getRequestURI()).setData(errors);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        Map<String, Collection<String>> errors = fetchBindingErrors(e.getBindingResult());
        return Result.error(WebCode.ARG_INVALID, request.getRequestURI()).setData(errors);
    }

    private Map<String, Collection<String>> fetchBindingErrors(BindingResult bindingResult) {
        List<FieldError> errors = bindingResult.getFieldErrors();
        ListMultimap<String, String> fieldErrors = ArrayListMultimap.create();
        errors.forEach(error -> fieldErrors.put(error.getField(), error.getDefaultMessage()));
        return fieldErrors.asMap();
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleConstraintViolationException(ConstraintViolationException exception, HttpServletRequest request) {
        Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
        return Result.error(WebCode.ARG_INVALID, request.getRequestURI()).setData(violations.iterator().next().getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result handleHttpMessageNotReadableException(HttpMessageNotReadableException e,
                                                        HttpServletRequest request) {
        log.error("参数解析失败, uri={}, 详情：{}", request.getRequestURI(), e.getMessage());
        return Result.error(WebCode.BAD_REQUEST, request.getRequestURI());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result handleMissingServletRequestParameterException(MissingServletRequestParameterException e,
                                                                HttpServletRequest request) {
        log.error("缺少请求参数, uri={}, 详情：{}", request.getRequestURI(), e.getMessage());
        return Result.error(WebCode.ARG_INVALID.getCode(), e.getMessage(), request.getRequestURI());
    }

    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e,
                                                               HttpServletRequest request) {
        log.error("不支持当前请求方法, uri={}, 详情：{}", request.getRequestURI(), e.getMessage());
        return Result.error(WebCode.METHOD_NOT_ALLOWED, request.getRequestURI());
    }

    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupportedException(HttpMediaTypeNotSupportedException e,
                                                               HttpServletRequest request) {
        log.error("不支持当前媒体类型, uri={}, 详情：{}", request.getRequestURI(), e.getMessage());
        return Result.error(WebCode.UNSUPPORTED_MEDIA_TYPE, request.getRequestURI());
    }


    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessException(BusinessException e,
                                          HttpServletRequest request) {
        log.error("业务异常", e);
        return Result.error(e.getCode(), e.getMessage(), request.getRequestURI());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(PersistenceException.class)
    public Result handlePersistenceException(Exception e, HttpServletRequest request) {
        log.error("数据库连接失败", e);
        return Result.error(WebCode.ERROR, e.getMessage(), request.getRequestURI());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(UnsupportedOperationException.class)
    public Result handleUnsupportedOperationException(Exception e, HttpServletRequest request) {
        log.error("不支持的数据类型, uri={}, 详情：{}", request.getRequestURI(), e.getMessage());
        return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), request.getRequestURI());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e,
                                                            HttpServletRequest request) {
        log.error("方法参数类型不匹配异常, uri={}, 详情：{}", request.getRequestURI(), e.getMessage());
        return Result.error(WebCode.ARG_INVALID.getCode(), "方法参数类型不匹配", request.getRequestURI());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(SysErrorException.class)
    public Result handleSysErrorException(SysErrorException e,
                                          HttpServletRequest request) {
        log.error("系统异常", e);
        return Result.error(e.getError().getCode(), e.getMessage(), request.getRequestURI());
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AccessDeniedException.class)
    public Result handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        log.error("权限异常", e);
        return Result.error(WebCode.UNAUTHORIZED, e.getMessage(), request.getRequestURI());
    }

    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(AuthenticationException.class)
    public Result handleAuthenticationException(AuthenticationException e, HttpServletRequest request) {
        log.error("认证异常", e);
        return Result.error(WebCode.FORBIDDEN, e.getMessage(), request.getRequestURI());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e, HttpServletRequest request) {
        log.error("服务繁忙", e);
        return Result.error(WebCode.ERROR, request.getRequestURI());
    }
}
